let SIZE = 8;
const EMPTY = 0, BLACK = 1, WHITE = 2;
let board = [];
let currentPlayer = BLACK;

const boardDiv = document.getElementById('board');
const currentPlayerSpan = document.getElementById('current-player');
const scoreSpan = document.getElementById('score');
const restartBtn = document.getElementById('restart');
const modeSelect = document.getElementById('mode');
const undoBtn = document.getElementById('undo');
const historyDiv = document.getElementById('history');
const aiLevelSelect = document.getElementById('ai-level');
const boardSizeSelect = document.getElementById('board-size');
const customSizeInput = document.getElementById('custom-size');
let gameMode = 'pvp'; // pvp: 本地双人, ai: 人机对战
let history = [];
let winnerStats = { black: 0, white: 0, draw: 0 };
let aiLevel = 'easy';
let gameOver = false;

function setBoardSize(newSize) {
    SIZE = newSize;
    initBoard();
    renderBoard();
    if (gameMode === 'ai' && currentPlayer === WHITE) {
        setTimeout(aiMove, 400);
    }
}

boardSizeSelect.addEventListener('change', () => {
    if (boardSizeSelect.value === 'custom') {
        customSizeInput.style.display = '';
        customSizeInput.value = SIZE;
        customSizeInput.focus();
    } else {
        customSizeInput.style.display = 'none';
        setBoardSize(Number(boardSizeSelect.value));
    }
});
customSizeInput.addEventListener('change', () => {
    let val = Number(customSizeInput.value);
    if (val % 2 !== 0 || val < 4 || val > 32) {
        alert('请输入4~32之间的偶数！');
        customSizeInput.value = SIZE;
        return;
    }
    setBoardSize(val);
});

modeSelect.addEventListener('change', () => {
    gameMode = modeSelect.value;
    restartBtn.click();
});

aiLevelSelect.addEventListener('change', () => {
    aiLevel = aiLevelSelect.value;
    if (gameMode === 'ai') restartBtn.click();
});

function initBoard() {
    board = Array.from({ length: SIZE }, () => Array(SIZE).fill(EMPTY));
    // 初始四子（中心4格）
    let mid1 = SIZE / 2 - 1, mid2 = SIZE / 2;
    board[mid1][mid1] = WHITE;
    board[mid1][mid2] = BLACK;
    board[mid2][mid1] = BLACK;
    board[mid2][mid2] = WHITE;
    currentPlayer = BLACK;
    history = [];
    gameOver = false;
    updateHistory();
}

function renderBoard() {
    boardDiv.innerHTML = '';
    // 动态计算格子大小
    const maxBoardPx = Math.min(window.innerWidth, window.innerHeight) * 0.65;
    const cellSize = Math.max(16, Math.floor(maxBoardPx / SIZE)); // 最小16px
    const pieceSize = Math.floor(cellSize * 0.7);
    boardDiv.style.gridTemplateColumns = `repeat(${SIZE}, ${cellSize}px)`;
    boardDiv.style.gridTemplateRows = `repeat(${SIZE}, ${cellSize}px)`;
    for (let r = 0; r < SIZE; r++) {
        for (let c = 0; c < SIZE; c++) {
            const cell = document.createElement('div');
            cell.className = 'cell';
            cell.style.width = cell.style.height = cellSize + 'px';
            cell.dataset.row = r;
            cell.dataset.col = c;
            if (board[r][c] !== EMPTY) {
                const piece = document.createElement('div');
                piece.className = 'piece ' + (board[r][c] === BLACK ? 'black' : 'white');
                piece.style.width = piece.style.height = pieceSize + 'px';
                if (history.length && history[history.length-1].flips.some(([fr,fc])=>fr===r&&fc===c) && history[history.length-1].player!==board[r][c]) {
                    piece.classList.add('flipping');
                }
                cell.appendChild(piece);
            }
            cell.addEventListener('click', onCellClick);
            boardDiv.appendChild(cell);
        }
    }
    updateInfo();
}

function updateInfo() {
    const [black, white] = countPieces();
    currentPlayerSpan.textContent = `当前轮到：${currentPlayer === BLACK ? '黑棋' : '白棋'}`;
    scoreSpan.textContent = `黑棋: ${black} | 白棋: ${white}`;
    const statsDiv = document.getElementById('stats');
    if (statsDiv) {
        statsDiv.textContent = `累计胜负：黑${winnerStats.black} | 白${winnerStats.white} | 平${winnerStats.draw}`;
    }
}

function countPieces() {
    let black = 0, white = 0;
    for (let r = 0; r < SIZE; r++) {
        for (let c = 0; c < SIZE; c++) {
            if (board[r][c] === BLACK) black++;
            if (board[r][c] === WHITE) white++;
        }
    }
    return [black, white];
}

function getAllValidMoves(player) {
    let moves = [];
    for (let r = 0; r < SIZE; r++) {
        for (let c = 0; c < SIZE; c++) {
            if (board[r][c] === EMPTY && getFlips(r, c, player).length > 0) {
                moves.push([r, c]);
            }
        }
    }
    return moves;
}

function onCellClick(e) {
    if (gameOver) return;
    if (gameMode === 'ai' && currentPlayer === WHITE) return;
    const r = parseInt(e.currentTarget.dataset.row);
    const c = parseInt(e.currentTarget.dataset.col);
    if (board[r][c] !== EMPTY) return;
    const flips = getFlips(r, c, currentPlayer);
    if (flips.length === 0) return;
    saveHistory(r, c, flips);
    board[r][c] = currentPlayer;
    for (const [fr, fc] of flips) {
        board[fr][fc] = currentPlayer;
    }
    currentPlayer = 3 - currentPlayer;
    renderBoard();
    setTimeout(() => {
        nextTurn();
    }, 350);
}

function getFlips(r, c, player) {
    const directions = [
        [-1, -1], [-1, 0], [-1, 1],
        [0, -1],          [0, 1],
        [1, -1], [1, 0], [1, 1]
    ];
    let flips = [];
    for (const [dr, dc] of directions) {
        let nr = r + dr, nc = c + dc;
        let temp = [];
        while (nr >= 0 && nr < SIZE && nc >= 0 && nc < SIZE && board[nr][nc] === 3 - player) {
            temp.push([nr, nc]);
            nr += dr;
            nc += dc;
        }
        if (temp.length > 0 && nr >= 0 && nr < SIZE && nc >= 0 && nc < SIZE && board[nr][nc] === player) {
            flips = flips.concat(temp);
        }
    }
    return flips;
}

function saveHistory(r, c, flips) {
    // 保存当前棋盘快照、落子、翻转、当前玩家
    history.push({
        board: board.map(row => row.slice()),
        move: [r, c],
        flips: flips.slice(),
        player: currentPlayer
    });
    updateHistory();
}

function updateHistory() {
    if (!history.length) {
        historyDiv.textContent = '暂无历史记录';
        return;
    }
    let html = `<b>历史记录（共${history.length}步）：</b><br>`;
    history.forEach((h, i) => {
        html += `${i+1}. ${h.player===BLACK?'黑':'白'}落子 [${h.move[0]+1},${h.move[1]+1}]，翻转${h.flips.length}子`;
        html += '<br>';
    });
    historyDiv.innerHTML = html;
}

function undoBtnClick() {
    if (history.length === 0) return;
    if (gameMode === 'ai') {
        // 人机对战，悔棋时撤销玩家和AI各一步
        if (history.length >= 2) {
            history.pop(); // 撤销AI
            const last = history.pop(); // 撤销玩家
            for (let r = 0; r < SIZE; r++) {
                for (let c = 0; c < SIZE; c++) {
                    board[r][c] = last.board[r][c];
                }
            }
            currentPlayer = last.player;
        } else {
            // 只剩一步时，撤销一步
            const last = history.pop();
            for (let r = 0; r < SIZE; r++) {
                for (let c = 0; c < SIZE; c++) {
                    board[r][c] = last.board[r][c];
                }
            }
            currentPlayer = last.player;
        }
    } else {
        // 双人对战，悔棋只撤销一步
        const last = history.pop();
        for (let r = 0; r < SIZE; r++) {
            for (let c = 0; c < SIZE; c++) {
                board[r][c] = last.board[r][c];
            }
        }
        currentPlayer = last.player;
    }
    gameOver = false;
    updateHistory();
    renderBoard();
}

function hasValidMove(player) {
    for (let r = 0; r < SIZE; r++) {
        for (let c = 0; c < SIZE; c++) {
            if (board[r][c] === EMPTY && getFlips(r, c, player).length > 0) {
                return true;
            }
        }
    }
    return false;
}

function endGame() {
    if (gameOver) return;
    gameOver = true;
    const [black, white] = countPieces();
    let msg = `游戏结束！\n黑棋: ${black} | 白棋: ${white}\n`;
    if (black > white) { msg += '黑棋胜利！'; winnerStats.black++; }
    else if (white > black) { msg += '白棋胜利！'; winnerStats.white++; }
    else { msg += '平局！'; winnerStats.draw++; }
    msg += `\n累计胜负：黑${winnerStats.black} | 白${winnerStats.white} | 平${winnerStats.draw}`;
    updateInfo();
    setTimeout(() => alert(msg), 100);
}

function nextTurn() {
    if (gameOver) return;
    if (!hasValidMove(currentPlayer)) {
        if (hasValidMove(3 - currentPlayer)) {
            alert('无合法落子，轮到对方！');
            currentPlayer = 3 - currentPlayer;
        } else {
            endGame();
            return;
        }
    }
    renderBoard();
    if (gameMode === 'ai' && currentPlayer === WHITE) {
        setTimeout(aiMove, 400);
    }
}

function aiMove() {
    if (gameOver) return;
    let moves = [];
    for (let r = 0; r < SIZE; r++) {
        for (let c = 0; c < SIZE; c++) {
            if (board[r][c] === EMPTY && getFlips(r, c, WHITE).length > 0) {
                moves.push([r, c]);
            }
        }
    }
    if (moves.length === 0) {
        nextTurn();
        return;
    }
    let move;
    if (aiLevel === 'easy') {
        move = moves[Math.floor(Math.random() * moves.length)];
    } else if (aiLevel === 'normal') {
        // 选翻子最多的
        let maxFlips = -1;
        let bestMoves = [];
        for (const [r, c] of moves) {
            const flips = getFlips(r, c, WHITE).length;
            if (flips > maxFlips) {
                maxFlips = flips;
                bestMoves = [[r, c]];
            } else if (flips === maxFlips) {
                bestMoves.push([r, c]);
            }
        }
        move = bestMoves[Math.floor(Math.random() * bestMoves.length)];
    } else {
        // hard: 优先角、其次边、再翻子多
        const corners = [[0,0],[0,7],[7,0],[7,7]];
        let cornerMove = moves.find(([r,c])=>corners.some(([cr,cc])=>cr===r&&cc===c));
        if (cornerMove) move = cornerMove;
        else {
            let edgeMoves = moves.filter(([r,c])=>r===0||r===7||c===0||c===7);
            if (edgeMoves.length) {
                // 边上选翻子最多
                let maxFlips = -1, bestEdgeMoves = [];
                for (const [r, c] of edgeMoves) {
                    const flips = getFlips(r, c, WHITE).length;
                    if (flips > maxFlips) {
                        maxFlips = flips;
                        bestEdgeMoves = [[r, c]];
                    } else if (flips === maxFlips) {
                        bestEdgeMoves.push([r, c]);
                    }
                }
                move = bestEdgeMoves[Math.floor(Math.random() * bestEdgeMoves.length)];
            } else {
                // 其它位置选翻子最多
                let maxFlips = -1, bestMoves = [];
                for (const [r, c] of moves) {
                    const flips = getFlips(r, c, WHITE).length;
                    if (flips > maxFlips) {
                        maxFlips = flips;
                        bestMoves = [[r, c]];
                    } else if (flips === maxFlips) {
                        bestMoves.push([r, c]);
                    }
                }
                move = bestMoves[Math.floor(Math.random() * bestMoves.length)];
            }
        }
    }
    const [r, c] = move;
    const flips = getFlips(r, c, WHITE);
    saveHistory(r, c, flips);
    board[r][c] = WHITE;
    for (const [fr, fc] of flips) {
        board[fr][fc] = WHITE;
    }
    currentPlayer = BLACK;
    renderBoard();
    setTimeout(() => {
        nextTurn();
    }, 350);
}

restartBtn.onclick = () => {
    initBoard();
    renderBoard();
    if (gameMode === 'ai' && currentPlayer === WHITE) {
        setTimeout(aiMove, 400);
    }
};

undoBtn.onclick = undoBtnClick;

// 初始化
initBoard();
renderBoard();

window.addEventListener('resize', () => {
    renderBoard();
}); 